package com.cloudwise.controller;

import com.cloudwise.service.UserInfoService;
import com.cloudwise.service.impl.UserInfoServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2021/9/13 10:09
 * @description：登录控制器
 * @modified By：
 * @version: 1.0
 */
@WebServlet( urlPatterns = "/login")
public class LoginServlet  extends HttpServlet {
    UserInfoService userInfoService= new UserInfoServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应的编码格式
   /*     req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");*/
        //获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //开始写业务方法
        Map<String, Object> user = userInfoService.findUserByUserNameAndPassword(username, password);
        String  message;
        HttpSession session = req.getSession();
        if(user!=null||(session.getAttribute("sessionUseranme")!=null)){
            if(session.getAttribute("sessionUseranme")==null){
                session.setAttribute("sessionUseranme",user.get("username"));
            }
            req.getRequestDispatcher("showUser.html").forward(req,resp);
        }else{
            //判断数据库用户名是否存在
            Map<String, Object> userName = userInfoService.findUserByUserName(username);
            ServletContext application= getServletContext();
            application.removeAttribute("myUsernameApplication");
            if(userName!=null){
                //用户名存在，密码不正确
                message="密码不正确！";
            }else
            {
                //用户名不存在
                message="用户名不存在！";
            }
            //session.setAttribute("message",message);
            //封装多个key  value  到map中
            Map  map = new HashMap();
            map.put("message",message);
            map.put("code", 500);
         /*   getServletContext().setAttribute("message",message);
            getServletContext().setAttribute("code",500);*/
            getServletContext().setAttribute("myResult",map);
            resp.sendRedirect("login.jsp");
           /* //登录失败

            //重定向，url地址变化，request中的值丢失，但是session中的值还在
            req.setAttribute("username","xxxx");
            session.setAttribute("sessionUseranme","xxxx");
            resp.sendRedirect("fail.jsp");*/

        }
    }

    @SuppressWarnings(value = "deprecation")
    public static void main(String[] args) {
        String  str= new String (new byte[1024],10000);
    }
}
